// pages/myidentityList/myidentityList.js
//logs.js
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
var timeOut = 59;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    disableSaleCar: false,
    authCode: '',
    mobile: '',
    showModal: false,
    tipsCode: "获取验证码",
    timeNum: 59,
    clikType: false,
    currentTab: 0,
    userType: '',
    chiceid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var role = []
    // var list = {
    //   roleName: "成为员工",
    //   elishRoleName: "Visitors",
    //   icon: '',
    //   bgstart: '#ff9f3c',
    //   bgend: '#ff9f3c',
    //   bg: 1,
    // }

    // role.push(list);
    // var list = {
    //   roleName: "已备案",
    //   elishRoleName: "Park administrator ",
    //   icon: '',
    //   bgstart: '#2666FC',
    //   bgend: '#54B0F1',
    //   bg: 2,
    // }
    // role.push(list);
    // var list = {
    //   roleName: "成为租户",
    //   elishRoleName: "Tenant",
    //   icon: '',
    //   bgstart: '#2666FC',
    //   bgend: '#54B0F1',
    //   bg: 2,
    // }
    // role.push(list);
    var list = {
      roleName: "游客",
      elishRoleName: "Owner",
      icon: '',
      bgstart: '#ff9f3c',
      bgend: '#ff9f3c',
      bg: 1,
      id: 5
    }
    role.push(list);

    this.data.role = role;
    // this.(this.data);
    this.setData({
      role: role
    })
   
      // 查看是否授权
      wx.getSetting({
        success: function(res){
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function(res) {
                console.log(res.userInfo)
                //用户已经授权过
              }
            })
          }
        }
      })
  },
  
  login (res) {
    console.log(res)
    var userInfo = JSON.parse(res.detail.rawData);
    var that = this;
    if (that.data.disableEnteringDatabase) {
      return;
    }
   
    if (userInfo) {
      //将用户信息赋值给app.globalData.userInfo
      for (var pro in userInfo) {
        app.globalData.userInfo[pro] = userInfo[pro];
      }
      //将用户信息缓存下来
      wx.setStorageSync('USER_INFO', userInfo);
      //调用
      if (userInfo.bindPhone) {
        wx.reLaunch({
          url: '../index/index',
        })
      } else {
        app.getUserInfo();
      }
    } else {
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    }
    setTimeout(function () {
      that.setData({
        disableEnteringDatabase: false
      })
    }, 1000);
  },
  chioce(e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    //var chiceid = e.currentTarget.dataset.id;
    wx.getUserInfo({
      success: function(res) {
        // console.log(res)
        wx.removeStorageSync('USER_INFO')
        console.log(res)
        var userInfo =res.userInfo;
        var that = this;
       
        if (userInfo) {
          //将用户信息赋值给app.globalData.userInfo
          for (var pro in userInfo) {
            app.globalData.userInfo[pro] = userInfo[pro];
          }
          console.log(app.globalData)
          //将用户信息缓存下来
          wx.setStorageSync('USER_INFO', userInfo);
        // var userInfo = res.userInfo
        // var nickName = userInfo.nickName
        // var avatarUrl = userInfo.avatarUrl
        // var gender = userInfo.gender //性别 0：未知、1：男、2：女
        // var province = userInfo.province
        // var city = userInfo.city
        // var country = userInfo.country
      }
    }
    })
    // wx.getPhoneNumber({
      // success:function(res){
          // console.log(res)
      // }
    // })
    this.setData({
      selected: index,
    });

    switch (index) {
      case 0:
        this.openzp();
        this.setData({
          userType: 'vistor'
        })
        // wx.navigateTo({
        //   url: '../Employee_certification/Employee_certification',
        // })
        break;
      case 1:
        this.openzp();
        this.setData({
          userType: 'filed'
        })
        break;
      case 2:
        wx.navigateTo({
          url: '../tenantCertification/tenantCertification',
        })
        break;
      case 3: //游客
        this.openzp();
        this.setData({
          userType: 'vistor'
        })
        // wx.redirectTo({
        //    url: '../index/index',
        // })
        break;
    }
  },
  go: function () {
    this.setData({
      showModal: false
    })
  },

  calsubmit() {
    var that = this
    let url = '';

    if (!that.data.calcontent) {
      util.showModal('请填写退回备注');
      return
    }
    var id = wx.getStorageSync("id");


    if (that.data.model == 'm1') {
      url = applet_park_api_url + '/api/repairs/return'

    }
    if (that.data.model == 'm2') {
      url = applet_park_api_url + '/api/repairs/cancel'

    }

    wx.request({
      url: url,
      data: {
        repairId: that.data.workid,
        assignorId: id,
        reason: that.data.calcontent
      },
      method: 'PUT',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: function (res) {

        if (res.data.code) {
          // wx.showToast({
          //   title: '操作成功',
          // })
          that.data.items = [];
          that.setData(that.data);
          that.setData({
            showModal: false
          })
          that.loadData();
          wx.reLaunch({
            url: '../index/index',
          })
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '微信获取用户信息失败',
          icon: 'none'
        })
      }
    })
  },
  openzp: function (e) {
    // var workid = e.currentTarget.dataset.workid;
    // var model = e.currentTarget.dataset.model;
    this.setData({
      showModal: true,

    })
  },

  selectlogo: function (e) {
    var that = this;
    if (that.data.currentTab === e.currentTarget.dataset.index) {
      return false;
    } else {
      that.setData({
        currentTab: e.currentTarget.dataset.index
      })
    }
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },
  checkPhone(e) {
    this.setData({
      mobile: e.detail.value
    })

  },

  // 点击获取手机验证码
  clickGainCode(e) {
    // if (this.data.disableSaleCar) {
    //   return;
    // }
    // this.setData({
    //   disableSaleCar: true
    // });
    if (!this.data.clikType) {
      this.gainCode();
    }
    // var that = this;
    // setTimeout(function () {
    //   that.setData({
    //     disableSaleCar: false
    //   })
    // }, 1000);

  },
  //输入手机号获取验证码
  gainCode() {

    var that = this;

    if (this.data.mobile == '' || this.data.mobile == null) {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
      })
    } else {
      that.setData({
        clikType: true
      })
      if (that.data.timeNum < timeOut) {} else {
        that.getTime();
        wx.request({
          url: applet_park_api_url + '/api/sendSms',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: "POST",
          data: {
            phoneNumber: this.data.mobile
          },
          success: function (res) {
            console.log(res)
            if (res.data.code == 0) {

              if (res.data.success) {} else {}
            } else {
              // wx.showToast({
              //   title: res.data.message,
              //   icon: 'none',
              // }) 
            }

          }
        })
      }
    }
  },
  //获取验证码时候显示时间
  getTime() {
    var that = this;
    var timer = setInterval(function () {
      that.data.timeNum--;
      if (that.data.timeNum <= 0) {
        that.setData({
          tipsCode: "重新获取验证码",
          timeNum: timeOut,
          clikType: false
        });
        clearInterval(timer);
      } else {
        that.setData({
          tipsCode: "发送" + that.data.timeNum + "秒",
        })
      }
    }, 1000)
  },
  getOpenid: function () { //获取openid 和 session_key
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.request({
            url: that.globalData.applet_park_api_url + '/api/wechatApplet/jscode2session',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              jsCode: res.code,
            },
            success: function (res1) {
              if (res1.data) {
                wx.setStorageSync("OPENID", res1.data.data.openid);
                wx.setStorageSync("SESSION_KEY", res1.data.data.session_key);
                that.globalData.openId = res1.data.data.openid; //绑定全局openid
              } else {
                wx.showToast({
                  title: '获取用户信息失败',
                  icon: 'fail'
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '获取用户信息失败',
                icon: 'fail'
              });
            }
          })
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'fail'
          });
        }
      }
    });
  },
  // 设置并登录
  submit: function () {
    if (!this.data.mobile) {
      util.showModal('请填写手机号');
      return;
    }
    if (!this.data.authCode) {
      util.showModal('请填写验证码');
      return;
    }
    var openId = app.globalData.openId 
    var userInfo = app.globalData.userInfo 
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/sysUsers/validatePhone',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'PUT',
      data: {
        phoneNumber: that.data.mobile,
        verificationCode: that.data.authCode,
        wxOpenId: openId,
        nickName: userInfo.nickName
      },
      success: function (res) {
        if (res.data.code == 0) {
          var userInfo = wx.getStorageSync("USER_INFO");
          if (userInfo) {
            userInfo.bindPhone = res.data.mobile;
            userInfo.nickName = res.data.nickName;
          }
          wx.setStorageSync("USER_INFO", userInfo);
          wx.setStorageSync("nickName", res.data.data.nickName);
          wx.setStorageSync("id", res.data.data.id);
          wx.setStorageSync("userRoles", res.data.data.userRoles);
          app.globalData.userRoles = res.data.data.userRoles; //保存角色
          app.globalData.id = res.data.data.id; //保存用户id
          app.globalData.nickName = res.data.data.nickName; //保存用户昵称
          app.globalData.userInfo = res.data.data.userInfo; //保存用户信息

          wx.showToast({
            title: '登录成功',
            icon: 'success',
          })
          // wx.switchTab({
          //   url: '../index/index',
          // })
          wx.redirectTo({
            url: '../index/index',
          })

        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function (res) {
        util.showModal('服务器开小差,请稍后重试');
      }
    });
  },
  //游客登录
  submitEnter() {
    if (!this.data.mobile) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return false;
    }
    //  app.getOpenid()
    //  console.log(app.globalData)
    var userInfo = app.globalData.userInfo || wx.getStorageSync("USER_INFO");
    wx.request({
      url: applet_park_api_url + '/api/visitorRegister/regist',
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        phone: this.data.mobile,
        wxOpenId: app.globalData.openId,
        nickName: userInfo.nickName
      },
      success: function (res) {
        if (res.data.wxOpenId != '') {
          var userInfo = wx.getStorageSync("USER_INFO");
          if (res.data.mobile || res.data.nickName) {
            userInfo.bindPhone = res.data.mobile;
            userInfo.nickName = res.data.nickName;
          }
          wx.setStorageSync("USER_INFO", userInfo);
          wx.setStorageSync("nickName", res.data.nickName);
          wx.setStorageSync("id", res.data.id);
          wx.setStorageSync("userRoles", res.data.userRoles);
          app.globalData.userRoles = res.data.userRoles; //保存角色
          app.globalData.id = res.data.id; //保存用户id
          app.globalData.nickName = res.data.nickName; //保存用户昵称
          app.globalData.userInfo = res.data.userInfo; //保存用户信息
          
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          wx.reLaunch({
            url: '../index/index',
          })

        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器开小差,请稍后重试',
          icon: 'none',
          duration: 3000
        })
      }
    });
  },
  getPhoneNumber(res){
    console.log(res)
    if(res.detail.encryptedData){
      // this.setData()
      var userInfo = app.globalData.userInfo || wx.getStorageSync("USER_INFO");
      wx.request({
        url: applet_park_api_url + '/api/visitorRegister/regist',
        header: {
          'content-type': 'application/json'
        },
        method: 'POST',
        data: {
          encryptedData: res.detail.encryptedData,
          wxOpenId: app.globalData.openId,
          nickName: userInfo.nickName,
          iv: res.detail.iv,
          session_key: wx.getStorageSync("SESSION_KEY")
        },
        success: function (res) {
          if (res.data.wxOpenId != '') {
            var userInfo = wx.getStorageSync("USER_INFO");
            if (res.data.mobile || res.data.nickName) {
              userInfo.bindPhone = res.data.mobile;
              userInfo.nickName = res.data.nickName;
            }
            wx.setStorageSync("USER_INFO", userInfo);
            wx.setStorageSync("nickName", res.data.nickName);
            wx.setStorageSync("id", res.data.id);
            wx.setStorageSync("userRoles", res.data.userRoles);
            app.globalData.userRoles = res.data.userRoles; //保存角色
            app.globalData.id = res.data.id; //保存用户id
            app.globalData.nickName = res.data.nickName; //保存用户昵称
            app.globalData.userInfo = res.data.userInfo; //保存用户信息
            
            wx.showToast({
              title: '登录成功',
              icon: 'none'
            })
            wx.reLaunch({
              url: '../index/index',
            })
  
          } else {
            wx.showToast({
              title: '登录失败',
              icon: 'none',
              duration: 3000
            })
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '服务器开小差,请稍后重试',
            icon: 'none',
            duration: 3000
          })
        }
      });

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})